const express=require('express');
const mysql=require('mysql');
const urlobj=require('url');
//引用自定义
const commte=require('../../../libs/common.js');
//链接数据库
var db=mysql.createPool({
    host:'localhost',
    user:'root',
    password:'',
    database:'leasedb'
});
//业务逻辑
module.exports = function() {
    var router = express.Router();
    //开始渲染后台首页
    //加载一级分类全部
    router.get("/AddTheSecondary.html",function(req,res,next){
        //判断是否登陆
        if(req.session['userId']==null||req.session['userId']=="")
        {
            res.status(400).send('<script>alert("请登录");window.location.href="login.html";</script>').end();
        }
        db.query("SELECT * FROM classa",function(err,data){
            if(err)
            {
                res.status(500).send('<script>alert("出错啦");</script>').end();
            }else
            {
                if(data.length==0)
                {
                    res.status(400).send('<script>alert("没有数据!");window.location.href="updateTheSecondary.html";</script>').end();
                }else {
                    req.Namecont=data;

                }
                next();
            }
        })
    });
    //添加二级分类
    router.use('/AddPrimaryClassification',function(req,res){

        db.query("SELECT * FROM `classb` WHERE classBName='"+req.body.classbclassBName+"'",function(err,data){
            //查询当前添加的一级分类是否添加过
            if(err)
            {
                res.status(400).send('<script>alert("操作失败");</script>').end();
            }
            if(data)
            {
                var cont=data.length;
                if(cont>0)
                {
                    res.status(400).send('<script>alert("存在该分类");window.location.reload();</script>').end();
                }else if(cont==0)
                {
                    // if(req.body.classaID==""||req.body.classaID==null)
                    // {
                    //     es.status(400).send('<script>alert("请选择一级分类");window.location.href="TheSecondary.html";</script>').end();
                    //     return false;
                    // }
                    db.query("INSERT INTO `classb`(`classBId`, `classBName`, `classAId`,`classBtime`) VALUES (0,'"+req.body.classbclassBName+"',"+(+req.body.classaID)+",'"+commte.getTime()+"')",function (err,data) {
                        if(err)
                        {
                            res.status(400).send('<script>alert("添加失败");</script>').end();
                        }
                        if(data)
                        {
                            res.status(400).send('<script>alert("添加成功");window.location.href="TheSecondary.html";</script>').end();
                        }
                    })
                }
            }
        });
    });

      router.get('/AddTheSecondary.html',function(req,res){
          res.render("admin/AddTheSecondary.ejs",{classcont:req.Namecont});
      });
    return router;
}